package com.xjk.ggbp_back.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@ControllerAdvice
public class GlobalExceptionHandler {



    // 可以添加更多的异常处理方法
    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<String> handleNotLoginException(NotLoginException ex) {
        JSONObject json = new JSONObject();
        json.put("code", 401);
        json.put("msg", "未登录");
        json.put("data", ex.getMessage());

        return new ResponseEntity<>(json.toJSONString(), HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public ResponseEntity handleNoResourceFoundException(NoResourceFoundException ex){
        JSONObject json = new JSONObject();
        json.put("code", 404);
        json.put("msg", "资源不存在");
        json.put("data", ex.getMessage());
        return new ResponseEntity<>(json.toJSONString(), HttpStatus.NOT_FOUND);
    }



    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        // 记录日志或其他操作
        JSONObject json = new JSONObject();
        json.put("code", 500);
        json.put("msg", "系统错误");
        json.put("data", ex.getMessage());

        ex.printStackTrace();
        return new ResponseEntity<>(json.toJSONString(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}